package com.demo.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.parser.ISqlParser;
import com.baomidou.mybatisplus.extension.parsers.BlockAttackSqlParser;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class MybatisPlusConfig {

	@Bean
	public MybatisPlusInterceptor mybatisPlusInterceptor() {
		// MyBatis Plus分页插件
		MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
		interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
		return interceptor;
	}
	/**
	 * 操作时自动填充createdTime和lastModifiedTime
	 *
	 * @return
	 */
	@Bean
	public MetaObjectHandler metaObjectHandler() {
		return new MetaObjectHandler() {
			@Override
			public void insertFill(MetaObject metaObject) {
				Object createTime = getFieldValByName("createTime", metaObject);
				Object modifiedTime = getFieldValByName("modifiedTime", metaObject);
				if (createTime == null) {
					setFieldValByName("createTime", LocalDateTime.now(), metaObject);
				}
				if (modifiedTime == null) {
					setFieldValByName("modifiedTime", LocalDateTime.now(), metaObject);
				}
			}

			@Override
			public void updateFill(MetaObject metaObject) {
				setFieldValByName("modifiedTime", LocalDateTime.now(), metaObject);
			}
		};
	}
}
